package org.six11.olive3.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.six11.olive3.util.ImageUtil;
import org.six11.util2.Debug;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class ImageBroker extends HttpServlet {

  private DatabaseThing dbThing;

  public ImageBroker() throws NamingException {
    Context env = (Context) new InitialContext().lookup("java:comp/env");
    dbThing = new DatabaseThing((DataSource) env.lookup(InkBroker.DATASOURCE_NAME));
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {

    // 1: Parse the url string to figure out which image is specified, and what type it is.
    String requestedFile = req.getPathInfo().substring(1);
    String imgDirStr = getInitParameter("imgDir");
    File imgDir = new File(imgDirStr);
    if (!imgDir.exists()) {
      boolean res = imgDir.mkdirs() && imgDir.canRead() && imgDir.canWrite();
      if (res) {
        bug("Successfully made path '" + imgDir.getAbsolutePath()
            + "'. All images will be persistently cached there.");
      } else {
        bug(" ** Error with image directory '" + imgDir.getAbsolutePath() + "'");
        bug(" **   I can't create this directory, or read or write files there.");
        bug(" **   This is probably a problem with user permissions. Check which user your web ");
        bug(" **   application is running as, and ensure that user can create directories up to ");
        bug(" **   and including the one specified in the web.xml file. Bailing.");
        return;
      }
    }
    int typeIdx = requestedFile.indexOf('.');
    int modifyIdx = requestedFile.indexOf('-');
    int idIndexEnd = modifyIdx > 0 ? modifyIdx : typeIdx;
    String idStr = requestedFile.substring(0, idIndexEnd);
    int id = Integer.parseInt(idStr);
    String modify = null;
    if (modifyIdx > 0) {
      modify = requestedFile.substring(modifyIdx + 1, typeIdx);
    }
    String type = requestedFile.substring(typeIdx + 1);
    String contentType = "image/" + type;

    // 2: Check to see if the image file exists. If not, create it.
    File imgFile = new File(imgDir, requestedFile);
    if (!imgFile.exists()) {
      ImageUtil util = new ImageUtil(dbThing, imgDir);
      if (modify == null) {
        util.generateImage(id, type);
      } else {
        int newSize = Integer.parseInt(modify);
        util.generateImage(id, type, newSize, newSize, imgFile);
      }
      if (!imgFile.exists()) {
        bug("Unable to generate image file " + imgFile.getAbsolutePath() + ". Returning.");
        return;
      }
      bug("Created file: " + imgFile.getAbsolutePath());
    }

    // 3: Write the file to output using the correct content type.
    resp.setContentType(contentType);
    byte[] fileArray = getBytesFromFile(imgFile);
    ServletOutputStream ros = resp.getOutputStream();
    ros.write(fileArray, 0, fileArray.length);
    ros.close();
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    this.doGet(req, resp);
  }

  /**
   * The following function was taken from
   * http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html.
   */
  public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);
    long length = file.length();

    if (length > Integer.MAX_VALUE) {
      return new byte[0];
    }
    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
      offset += numRead;
    }
    if (offset < bytes.length) {
      throw new IOException("Could not completely read file " + file.getName());
    }
    is.close();
    return bytes;
  }

  private static void bug(String what) {
    Debug.out("ImageBroker", what);
  }
}
